﻿<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title>无标题文档</title>
    <style type="text/css">
        select {
            display: inline;
            width: 150px;
            background: #cef;
        }
    </style>
</head>

<body>
    <select size="10" id="selectleft">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
    </select>
    <input type="button" id="addto" value="添加" />
    <input type="button" id="moveback" value="删除" />
    <select size="10" id="selectright"></select>
    <script type="text/javascript">
        var addTo = document.getElementById("addto");
        var moveBack = document.getElementById("moveback");
        var selectLeft = document.getElementById("selectleft");
        var selectRight = document.getElementById("selectright");
        addTo.onclick = addOption;
        moveBack.onclick = delOption;


        //这个函数检验传入的值是否在有边出现过！
        function hasOption(str) {
            for (var i = 0; i < selectRight.options.length; i++) {
                if (selectRight.options[i].value == str) {
                    return false;
                }
            }
            return true;
        }


        function addOption() {
            var nowIndex = selectRight.options.length;              //右边的下一个索引
            var selectIndex = selectLeft.options.selectedIndex;        //做边被选种项索引
            var selectText = selectLeft.options[selectIndex].text;    //被选种项文本
            var selectValue = selectLeft.options[selectIndex].value;   //被选种项值

            if ((selectIndex != -1) && hasOption(selectValue)) {             //如果选了一项且右边没有，执行
                var newoption = new Option(selectText, selectValue, false, false);
                selectRight.options[nowIndex] = newoption;
            }
        }
        function delOption() {
            var selectIndex = selectRight.options.selectedIndex;
            if (selectIndex != -1) {
                selectRight.options[selectIndex] = null;                   //清空选种项
            }
        }

    </script>
</body>
</html>